package com.xltt.watchserver.blueth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;

import com.xltt.watchserver.utils.Logger;

public class BtServer extends BtBase{
    private static final String TAG = BtServer.class.getSimpleName();
    private BluetoothServerSocket mSSocket;
    private String mBluethName = "";

    public BtServer(Listener listener) {
        super(listener);
        listen();
    }

    /**
     * 监听客户端发起的连接
     */
    public void listen() {
        try {
            BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
//            mSSocket = adapter.listenUsingRfcommWithServiceRecord("BT", SPP_UUID); //加密传输，Android强制执行配对，弹窗显示配对码
            mBluethName = adapter.getName();
            mSSocket = adapter.listenUsingInsecureRfcommWithServiceRecord(mBluethName, SPP_UUID); //明文传输(不安全)，无需配对
            // 开启子线程
            new Thread(){
                @Override
                public void run() {
                    try {
                        BluetoothSocket socket = mSSocket.accept(); // 监听连接
                        mSSocket.close(); // 关闭监听，只连接一个设备
                        loopRead(socket); // 循环读取
                        Logger.d("蓝牙 = " + mBluethName +" 服务启动");
                    } catch (Throwable e) {
                        close();
                    }
                }
            }.start();
        } catch (Throwable e) {
            close();
        }
    }


    @Override
    public void close() {
        super.close();
        try {
            Logger.d("close()蓝牙 = " + mBluethName +" 服务关闭");
            mSSocket.close();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}
